package com.thank.web.interpector;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description: none
 *
 * @author thank
 * 2018/2/19 22:31
 */
@Component
public class TimeInterpector implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("TimeInterpector -> preHandle");
        System.out.println(((HandlerMethod) handler).getBean().getClass().getName());
        System.out.println(((HandlerMethod) handler).getMethod().getName());

        request.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("TimeInterpector -> postHandle");
        Long start = (Long) request.getAttribute("startTime");
        System.out.println("time interceptor 耗时: " + (System.currentTimeMillis()-start));

    }

    /**
     * 不管控制器返回成功还是失败, 都会进入该方法
     * @throws Exception 如果拦截的方法抛出异常, 会被Exception e接收
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        System.out.println("TimeInterpector -> afterCompletion");
        Long start = (Long) request.getAttribute("startTime");
        System.out.println("time interceptor 耗时: " + (System.currentTimeMillis()-start));
        System.out.println("Exception is : " + e);
    }
}
